#include "udp_sender.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

UdpSender::UdpSender() : udpSocket(-1) {}

UdpSender::~UdpSender() {
    close();
}

bool UdpSender::initialize(int port) {
    udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (udpSocket < 0) {
        std::cerr << "Cannot create UDP socket" << std::endl;
        return false;
    }

    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);

    if (bind(udpSocket, reinterpret_cast<struct sockaddr *>(&serverAddr), sizeof(serverAddr)) < 0) {
        std::cerr << "Failed to bind UDP socket" << std::endl;
        close();
        return false;
    }

    return true;
}

bool UdpSender::sendData(const void *data, size_t length, const sockaddr_in &clientAddr) {
    std::cout << "Attempting to send " << length << " bytes of data." << std::endl;
    size_t sent = 0;
    while (sent < length) {
        size_t remainingLen = length - sent;
        size_t packetSize = (remainingLen < MAX_PACKET_SIZE) ? remainingLen : MAX_PACKET_SIZE;

        ssize_t bytesSent = sendUdpPacket(static_cast<const char *>(data) + sent, packetSize, clientAddr);
        if (bytesSent < 0) {
            std::cerr << "Failed to send UDP packet" << std::endl;
            return false;
        }
        sent += bytesSent;
    }
    std::cout << "Successfully sent " << sent << " bytes of data." << std::endl;
    return true;
}

void UdpSender::close() {
    if (udpSocket >= 0) {
        ::close(udpSocket);
        udpSocket = -1;
    }
}

int UdpSender::sendUdpPacket(const void *data, size_t length, const sockaddr_in &clientAddr) {
    return sendto(udpSocket, data, length, 0,
                  reinterpret_cast<const struct sockaddr *>(&clientAddr),
                  sizeof(clientAddr));
}